package com.csx.micrometer.discovery.adapter;

import com.csx.micrometer.discovery.config.MicrometerDiscoveryProperties;
import com.csx.micrometer.discovery.annotation.RegistryCenter;
import com.csx.micrometer.discovery.model.InstanceDetailPojo;
import com.csx.micrometer.discovery.model.NamespaceDetail;
import com.csx.micrometer.discovery.model.ServicePojo;
import com.csx.micrometer.common.exception.MicrometerException;
import com.csx.micrometer.common.exception.MicrometerMessageEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * 兼容多种注册中心的实现，通过该Adapter做适配
 * @author cuisongxu
 * @date 2022/12/5 17:35
 */
@Component
public class RegistryCenterServiceAdapter implements RegistryCenterService {

    private RegistryCenterService registryCenterService;

    @Autowired
    private MicrometerDiscoveryProperties micrometerDiscoveryProperties;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        String registryType = micrometerDiscoveryProperties.getType();
        Map<String, RegistryCenterService> registryCenterServiceMap = applicationContext.getBeansOfType(RegistryCenterService.class);

        // 从容器中找出用户需要的注册中心类型的实现
        for (Map.Entry<String, RegistryCenterService> entry : registryCenterServiceMap.entrySet()) {
            RegistryCenterService registryCenterService = entry.getValue();
            RegistryCenter annotation = registryCenterService.getClass().getAnnotation(RegistryCenter.class);
            if(annotation != null && annotation.type().getName().equals(registryType)) {
                this.registryCenterService = registryCenterService;
            }
        }

        if(ObjectUtils.isEmpty(this.registryCenterService)) {
            throw new MicrometerException(MicrometerMessageEnum.NOT_EXIST_REGISTRY_CENTER_IMPL.getMessage());
        }
    }

    @Override
    public List<NamespaceDetail> getNamespaces() {
        return this.registryCenterService.getNamespaces();
    }

    @Override
    public List<ServicePojo> getServices(NamespaceDetail namespaceDetail) {
        return this.registryCenterService.getServices(namespaceDetail);
    }

    @Override
    public List<InstanceDetailPojo> getInstances(String namespace, ServicePojo servicePojo) {
        return this.registryCenterService.getInstances(namespace, servicePojo);
    }
}
